package com.zjzywl.smoke.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.zjzywl.smoke.repository.DeviceCustomRepository;
import com.zjzywl.smoke.entity.Device;
import com.zjzywl.smoke.entity.DeviceStatus;

@Repository
public class DeviceRepositoryImpl implements DeviceCustomRepository {
	@PersistenceContext
	private EntityManager em;

	public List findByUserAndDeviceTypeAndAddressLike(String userId, String deviceTypeId, String alarmCode,
			String address) {
		String sql = "select a.device from Alarm a where 1=1";
		System.out.println(validStr(alarmCode) + alarmCode);
		if (validStr(alarmCode)) {
			sql += " and a.alarmType.alarmCode=" + alarmCode;
		}
		if (validStr(address)) {
			sql += " and a.device.address like '" + address + "'";
		}
		sql += " and a.device in (" + " SELECT b.device FROM OrgDev b , SysUser c where b.organization.id=c.org.id "
				+ " and c.userId = " + userId + " and b.device.deviceType.deviceTypeId=" + deviceTypeId + ")";
		Query query = em.createQuery(sql);
		return query.getResultList();
	}

	public List getDeviceCountByUserAndDeviceType(String userId, String deviceTypeId) {
		String sql = " SELECT count(b) FROM OrgDev b , SysUser c where b.organization.id=c.org.id " + " and c.userId = "
				+ userId + " and b.device.deviceType.deviceTypeId=" + deviceTypeId;
		sql += " and b.device.Remove=null";
		Query query = em.createQuery(sql);
		return query.getResultList();
	}

	public List<Device> findByDevice(int orgId, String deviceTypeId) {

		String sql = " SELECT c FROM Device c where c.id in (select b.device.id from OrgDev b where b.organization.id ="
				+ orgId + " and b.device.Remove=null and  b.device.deviceType.deviceTypeId=" + deviceTypeId + ")";
		System.out.println(sql);
		Query query = em.createQuery(sql);
		return query.getResultList();
	}

	private Boolean validStr(String value) {
		return (value != null) && (value.length() != 0) && (!value.equals("null")) && (!value.equals("%null%"));
	}

	public Long findDeviceCountByUserAndDeviceTypeAndStatus(String userId, String devicetypeid, String status) {
		String sql = "select count(a) from DeviceStatus a where a.device in ("
				+ " SELECT b.device FROM OrgDev b , SysUser c where b.organization.id=c.org.id " + " and c.userId = "
				+ userId + " and b.device.deviceType.deviceTypeId=" + devicetypeid + ")";
		if (validStr(status)) {
			sql += " and a.status=" + status;
		}
		Query query = em.createQuery(sql);
		return (long) query.getSingleResult();

	}
	   


}
